﻿using Dapper;
using OMG.Fill.Vegetable.Model;
using OMG.Fill.Vegetable.Model.Ent;
using OMG.Fill.Vegetables.Service;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OMG.Fill.Vegetable.Service
{
    /// <summary>
    /// 角色表T_Role通用操作类
    /// </summary>
    public class RoleServices:Roles
    {
        public Pager<List<RoleModel>> GetPageList(RoleQuery query)
        {
            Pager<List<RoleModel>> obj = new Pager<List<RoleModel>>();
            var paramlist = new DynamicParameters();
            string strWhereSql = "";//from 表在下面，需完善其他查询条件在这里接的写，格式为："and xxx=@xxx空格,如下注释部分代码所示："
            if (!string.IsNullOrEmpty(query.RoleName.ToString().Trim()))
            {
                strWhereSql += "and RoleName like '%@RoleName%' ";
                paramlist.Add("RoleName", query.RoleName);
            }
            if (!string.IsNullOrEmpty(query.RoleType.ToString().Trim()))
            {
                strWhereSql += "and RoleType = @RoleType ";
                paramlist.Add("RoleType", query.RoleType);
            }
            if (!string.IsNullOrEmpty(query.Status.ToString().Trim()))
            {
                strWhereSql += "and Status = @Status ";
                paramlist.Add("Status", query.Status);
            }
            string strFromSql = "from dbo.T_Role where 1=1 " + strWhereSql;
            string strTotal = "select count(1)" + strFromSql + strWhereSql;
            string strOrderSql = "";//自定义完成order by语句
            string strSql = @"select * from (select *,ROW_NUMBER() over (order by Id ) as RowNumber " + strFromSql + ") as t ";
            strSql += "where t.RowNumber between  @minRow and @maxRow" + strOrderSql;
            paramlist.Add("minRow", query.MinRow);
            paramlist.Add("maxRow", query.MaxRow);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.rows = dbCon.Query<RoleModel>(strSql,paramlist).ToList();
                    foreach (var item in obj.rows)
                    {
                        item.StatusName = DataDict.Instance["StatusList"][item.Status];
                        item.RoleTypeName = DataDict.Instance["RoleType"][item.RoleType];
                    }
                    obj.total = dbCon.Query<int>(strTotal,paramlist).FirstOrDefault();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取角色表T_Role分页列表失败", ex);
                return obj;
            }
        }



        public ResResult<List<MenuTree>> getMenuTreeList(string roleId)
        {
            ResResult<List<MenuTree>> list = new ResResult<List<MenuTree>>();
            list.model = GetMenuTree(roleId, "");
            list.status = DefaultKey.SuccessResult;
            list.message = "获取菜单树列表成功！";
            return list;
        }

        /// <summary>
        /// 菜单树
        /// </summary>
        /// <param name="RoleId"></param>
        /// <param name="MenuId"></param>
        /// <returns></returns>
        public List<MenuTree> GetMenuTree(string RoleId, string MenuId)
        {
            List<MenuTree> listArea = new List<MenuTree>();
            MenuRoleServices Services = new MenuRoleServices();
            string strSql = @"select * from [dbo].[T_Menu] where ParentId=@MenuId and Status='1'";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    List<MenuEntity> tempList = dbCon.Query<MenuEntity>(strSql, new { MenuId = MenuId }).ToList();
                    foreach (var item in tempList)
                    {
                        MenuTree model = new MenuTree();
                        model.Id = item.Id;
                        model.title = item.MenuName;
                        model.ParentId = MenuId;
                        if (!string.IsNullOrEmpty(MenuId))
                        {
                            model.@checked = CheckMenuRole(RoleId, model.Id);
                        }
                        var childrenList = GetMenuTree(RoleId, model.Id);
                        model.expand = childrenList.Count == 0 ? false : true;
                        model.children = childrenList.Count == 0 ? null : childrenList;
                        listArea.Add(model);
                    }
                    return listArea;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("获取菜单树失败", ex);
                return listArea;
            }
        }

        /// <summary>
        /// 判定角色菜单是否存在
        /// </summary>
        /// <param name="roleid"></param>
        /// <param name="menuid"></param>
        /// <returns></returns>
        private Boolean CheckMenuRole(string roleid, string menuid)
        {
            try
            {
                string strSql = @"select count(1) from dbo.T_MenuRole where MenuId = @MenuId and RoleId = @RoleId";
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    if (dbCon.Query<int>(strSql, new { MenuId = menuid, RoleId = roleid }).FirstOrDefault() > 0 )
                        return true;
                    else
                        return false;
                }
            }
            catch
            {
                return false;
            }
        }
    }
}